package ru.evreke.ui

import Board
import ClientMessage
import Coordinates
import FieldConstants
import ShotMessage
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.launch
import org.jetbrains.compose.web.css.*
import org.jetbrains.compose.web.css.keywords.auto
import org.jetbrains.compose.web.dom.Div
import org.jetbrains.compose.web.dom.Text
import ru.evreke.ui.style.AppStylesheet

@Composable
fun Board(
    state: MutableState<Map<String, Map<String, Board>>>,
    sendChannel: Channel<ClientMessage>,
    scope: CoroutineScope
) {
    Div(
        attrs = {
            style {
                display(DisplayStyle.Flex)
                flexDirection(FlexDirection.Row)
                justifyContent(JustifyContent.SpaceEvenly)
                width(50.percent)
                property("margin", auto)
            }
        }
    ) {
        state.value.forEach { gameToPlayerByBoard ->
            Div(
                attrs = { classes(AppStylesheet.fieldContainer) }
            ) {
                gameToPlayerByBoard.value.forEach { playerToBoard ->
                    playerToBoard.value.field.mapIndexed { y, row ->
                        row.mapIndexed { x, cell ->
                            Div({
                                classes(AppStylesheet.fieldCell)
                                attr("data-x", x.toString())
                                attr("data-y", y.toString())
                                if (playerToBoard.value.isMasked) {
                                    // Add handler to opponent board
                                    onClick {
                                        scope.launch {
                                            sendChannel.send(
                                                ShotMessage(
                                                    gameToPlayerByBoard.key,
                                                    Coordinates(x, y)
                                                ) as ClientMessage
                                            )
                                        }
                                    }
                                }
                            }) {
                                cell.let {
                                    if (it != FieldConstants.EMPTY) {
                                        Text(cell.toString())
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
